//
//  PageContentView.swift
//  DYZB
//
//  Created by HOu on 2021/11/19.
//

import UIKit

protocol PageContentViewDelegate : AnyObject {
    func pageContentView(contentView:PageContentView,progress:CGFloat,sourceIndex:Int,targetIndex:Int)
}
private let ContentCellID = "ContentCellID"

class PageContentView: UIView {

    // MARK: - 存放子控制器
    private var childVcs: [UIViewController]
    private weak var parentVc: UIViewController?
    // MARK: - 保存偏移量
    private var startOffsetX : CGFloat = 0
    //禁止滚动代理 默认不禁止
    private var isForbidScrollDelegate : Bool = false
    weak var delegate : PageContentViewDelegate?
    
    // MARK: - 创建UICollectionView
    private lazy var collectionView:UICollectionView = {[weak self] in
        //在闭包里使用self 需要使用弱引用,防止循环引用
        //1.创建layout
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!//可选类型需要强制解包
        layout.minimumLineSpacing = 0 //行间距
        layout.minimumInteritemSpacing = 0 //每个item间距
        layout.scrollDirection = .horizontal //水平滚动
        
        //2.创建UICollectionView
        let collectionView = UICollectionView(frame: CGRect.zero,collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false//水平指示器不需要显示
        collectionView.isPagingEnabled = true //
        collectionView.bounces = false
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
        return collectionView
    }()

    /// 初始化构造函数
    /// - Parameters:
    ///   - frame: 传入尺寸大小
    ///   - childVcs: 有几个传几个控制器
    ///   - parentViewController: 再传入一个父控制器
    init(frame:CGRect,childVcs:[UIViewController],parentViewController:UIViewController?){
        self.childVcs = childVcs
        self.parentVc = parentViewController
        
        super.init(frame: frame)
        
        //设置UI
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    

}
// MARK: - 设置UI界面
extension PageContentView {
    private func setupUI() {
        //1.将所有的子控制器添加父控制器中
        for childVc in childVcs {
            parentVc?.addChild(childVc)
        }
        
        //2.添加UICollocationView,用于在cell中存放控制器的view
        addSubview(collectionView)
        collectionView.frame = bounds
    }
    
}
// MARK: - 遵守UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        //1.创建cell 从缓冲池中拿到cell  必须先注册cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
        //2.给cell 设置内容
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        
        let childVC = childVcs[indexPath.row]//取出vc
        childVC.view.frame = cell.contentView.bounds//设置大小
        cell.contentView.addSubview(childVC.view)
        
        return cell
    }
    
}

// MARK: - 遵守UICollectionViewDelegate
extension PageContentView : UICollectionViewDelegate {
    // MARK: - 开始拖拽
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //一但开始拖动
        isForbidScrollDelegate = false
        
        startOffsetX = scrollView.contentOffset.x
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //0.判断是否是点击事件
        if isForbidScrollDelegate {return}
        
        
        //1.定义获取需要的数据
        var progress:CGFloat = 0
        var soureIndex : Int = 0
        var targetIndex : Int = 0
        
        //2.判断是左滑还是右滑
        let currentOffsetX = scrollView.contentOffset.x
        let scrollViewW = scrollView.bounds.width
        if currentOffsetX > startOffsetX {//左滑
            //1.计算progress
            progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
            //2.计算sourceIndex
            soureIndex = Int(currentOffsetX / scrollViewW)
            //3.计算targetIndex
            targetIndex = soureIndex + 1
            if targetIndex >= childVcs.count {
                targetIndex = childVcs.count - 1
            }
            //4.如果完全划过去
            if currentOffsetX - startOffsetX == scrollViewW {
                progress = 1
                targetIndex = soureIndex
            }
        }else{//右滑
            //1.计算progress
            progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
            //2.计算targetIndex
            targetIndex = Int(currentOffsetX / scrollViewW)
            //3.计算scourceIndex
            soureIndex = targetIndex + 1
            if soureIndex >= childVcs.count {
                soureIndex = childVcs.count - 1
            }
        }
        //3.将progress/soureIndex/targetIndex传递给titleView
        print("progress:\(progress) soureIndex:\(soureIndex) targetIndex:\(targetIndex)")
        delegate?.pageContentView(contentView: self, progress: progress, sourceIndex:soureIndex , targetIndex: targetIndex)
    }
}



// MARK: - 对外暴露的方法
extension PageContentView {
    //从HomeViewVC调用该方法传入 currentIndex
    func setCurrentIndex(currentIndex:Int){

        //1.记录需要禁止执行代理方法
        isForbidScrollDelegate = true
        //2.滚到正确的位置
        let offSetX = CGFloat(currentIndex) * collectionView.frame.width
        collectionView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: false)
    }
    
    
}
